package com.bible.fire.util.http;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.dom4j.DocumentHelper;

import com.bible.fire.util.AndroidUtil;
import com.bible.fire.util.SystemConstant;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;

public class HttpThread extends Thread {
	
	 private Handler handle = null;
	 private HttpPost httpost = null;
	 private String startTime = "";
	 private String[] requestUrl = null;
	 private String[] fileformat = null;
	 private boolean isDownload = false;
	 private int connectionTimeout = -1;
	 private int socketTimeout = -1;
	 private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	 
	 public HttpThread(Handler hander){
         handle=hander;
     }
	 
	 public HttpThread(Handler hander, int connectionTimeout, int socketTimeout){
         handle=hander;
         this.connectionTimeout = connectionTimeout;
         this.socketTimeout = socketTimeout;
     }
	 
	 public void doStart( HttpPost httpost){
		 this.httpost = httpost;
		 this.start(); 
	 }

	 public void doStart( HttpPost httpost, boolean isDownload, String[] requestUrl, String[] fileformat){
		 this.httpost = httpost;
		 this.isDownload = isDownload;
		 this.fileformat = fileformat;
		 this.start();
	 }
	 
	 @Override
	 public void run(){
		 super.run();
		 startTime = sdf.format( new Date() );
		 Message msg = new Message();
		 Bundle b=new Bundle();
		 DefaultHttpClient httpclient = new DefaultHttpClient();
		 if( connectionTimeout > 0 ){
			 HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), connectionTimeout);
		 }
		 if( socketTimeout > 0 ){
			 HttpConnectionParams.setSoTimeout(httpclient.getParams(), socketTimeout);
		 }		 
     	 //HttpConnectionParams.setSoTimeout(params, timeout);
		 //httpclient.getParams().setParameter(name, value)
         try {
        	 if( isDownload){
        		 String[] filenames = new String[requestUrl.length];
        		 for( int i =0; i < requestUrl.length; i++ ){
        			 httpost.setURI( new URI(requestUrl[i]) );
        			 HttpResponse resp = httpclient.execute(httpost);
            		 StatusLine status = resp.getStatusLine();
            		 if( status.getStatusCode() == 200 ){
            			 String filename = DateFormat.format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + "." + fileformat[i];
            			 FileOutputStream fos = new FileOutputStream( SystemConstant.FILE_DOWNLOAD_PATH + filename);
            			 InputStream is = resp.getEntity().getContent();
            			 byte[] buffer = new byte[1024];
            			 int j = 0;
            			 while( (j = is.read(buffer)) != -1){
            				 fos.write(buffer, 0, j);
            			 }
            			 fos.flush();
            			 is.close();
            			 fos.close();
            			 Log.d("download file", filename);
            			 filenames[i] = filename;
            		 }
        		 }
        		 b.putStringArray("result", filenames);
        	 }else{
        		 ResponseHandler<String> responseHandler = new BasicResponseHandler();       	 
     	         String responseBody = httpclient.execute(httpost, responseHandler);
     	         Log.d("response body", responseBody);
     	         b.putString("result", responseBody);
        	 }       	 
 	         List<Cookie> cookies = httpclient.getCookieStore().getCookies();
 	         if( cookies != null && cookies.size() > 0 ){
 	        	for( Cookie cookie : cookies ){
 	        		if( cookie.getName().equals("JSESSIONID")){
 	        			AndroidUtil.setAttribute("sessionID", cookie.getValue() );
 	        			Log.d("sessionID", cookie.getValue() );
 	        			break;
 	        		}
 	        	}
 	         }               
	         msg.what = 1;	         
	         b.putString("startTime", startTime);
	         msg.setData( b );
		 }catch(Exception e) {
			Log.e("http", "call http error", e);
			msg.what = 0;
			b.putString("error", e.getMessage());
			msg.setData( b );
		 }finally {
		    httpclient.getConnectionManager().shutdown();
		 }
         handle.sendMessage( msg );
	 }

}
